// pages/zdarea/zdarea.js
var app = getApp()
var header = {
  'content-type': 'application/x-www-form-urlencoded',
  'cookie': "openid=" + app.globalData.openid
}
var timer = null
Page({
  /**
   * 页面的初始数据
   */
  data: {
    items: [],//列表
    choItem: {},// 已选择     
    firstsetupflag:true, //点击终端设置 显示新增 选择 显示模板的 开关参数
    setupflag: true,  //模板详细信息 弹出层
    selectTemplateflag:true,  //选择模板弹出层
    newtemplateflag:true, //新建模板弹出层
    types: [
      {name: '全夜灯', value: 0, checked: 'true' }, { name: '半夜灯', value: 1 }, { name: '清洁照明', value: 2 }, { name: '时段灯', value: 3 }
    ],   
    types_index:0,  //默认选中当前是那种类型的灯
    new_types_index:0, //新增模板默认是哪种类型的灯
    change_types_index:0, //切换模板默认的开关灯类型
    LightModal:[],//某个模板组下的所有模板,用户选择模板时使用[{\"turnOff\":\"auto\",\"turnOffChange\":\"1\",\"gid\":\"23\",\"modalType\":\"0\",\"turnOn\":\"auto\",\"name\":\"全夜灯\",\"id\":\"54\",\"turnOnChange\":\"1\",\"group\":\"无锡测试\"},{\"turnOff\":\"23:00:00\",\"turnOffChange\":\"0\",\"gid\":\"23\",\"modalType\":\"1\",\"turnOn\":\"auto\",\"name\":\"半夜灯\",\"id\":\"55\",\"turnOnChange\":\"-45\",\"group\":\"无锡测试\"},{\"turnOff\":\"15:35:00\",\"turnOffChange\":\"0\",\"gid\":\"23\",\"modalType\":\"3\",\"turnOn\":\"15:30:00\",\"name\":\"时段灯\",\"id\":\"57\",\"turnOnChange\":\"0\",\"group\":\"无锡测试\"}]"
    LightModal_index:0, //默认选中当前是那个模板
    change_LightModal_index:0, //从切换模板点进去 找到当前那个模板
    cur_LightModal:{}, //这个值表示当前具体是哪一个模板项 ，根据LightModal和LightModal_index可以找出来
    switchTypes:[{name:'指定时间', value:0},{name:'根据设备经纬度自动计算', value:1}],
    switchTypes_index:0, //开灯时间类型 
    switchTypes_off_index:0, //关灯时间类型
    new_switchTypes_index:1, //新建模板  开灯事件类型 默认选全夜灯 更具设备所在经纬度自动字段
    new_switchTypes_off_index:1,//新建模板 默认选全夜灯 关灯事件类型 更具设备所在经纬度自动字段
    change_switchTypes_index:0, //切换模板  开灯事件类型
    change_switchTypes_off_index:0,//切换模板 关灯事件类型
    lightType: 0, // 全夜灯 0，半夜灯 1，清洁照明 2,时段灯3
    ligthTypeStr:"",
    addVal: 0, // 日出调整量
    new_addVal: 0, // 新建目录 日出调整量
    change_addVal:0, //切换模板 日出调整量
    subVal: 0, // 日落调整量
    new_subVal: 0, //新建模板 日落调整量
    change_subVal: 0, //切换模板 日落调整量
    branchTypes: [],
    branch: [],
    halfLightOff: "--",
    cleanLightOn: "--",
    mid:'',
    district:'',
    id:'',
    district_loadTree_data:[],
    modalGroupID:'',
    ModalGroup:[],  //模板
    ModalGroupName:'', //模板name
    cur_group_id:'',  //模板id
    template_name:'', //模板名称input
    new_template_name:'', //新建模板名称input
    template_switch_type:'', //开关等类型picker
    template_turnon_type:'',//开灯时间类型 input
    special_turnon:'', //时段/清洁灯开灯时间 picker
    sun_off:'', //日落时间调整分钟数 input
    template_turnon_type:'',//关灯时间类型 picker
    special_turnoff:'', //时段/清洁灯关灯时间
    sun_up:'',//日出时间调整
    //timeparam_clear_lamp_disable:false, //时段/清洁灯开灯时间时间选择器是否可用 半夜等全夜灯不可用，时段灯清洁灯可用 默认不用，
    //new_timeparam_clear_lamp_disable:false, // 新建模板 时段/清洁灯开灯时间时间选择器是否可用 半夜等全夜灯不可用，时段灯清洁灯可用 默认不用，
    //change_timeparam_clear_lamp_disable:false, //切换模板 新建模板 时段/清洁灯开灯时间时间选择器是否可用
    timeparam_clear_lamp_turnon:'',//时段/清洁灯开灯时间
    new_timeparam_clear_lamp_turnon:'auto', //新建模板 时段/清洁灯开灯时间 一开始是全夜等 默认auto
    change_timeparam_clear_lamp_turnon:'',//切换模板 时段/清洁灯开灯时间
    timeparam_clear_lamp_turnoff:'',//时段/清洁灯关灯时间
    new_timeparam_clear_lamp_turnoff:'auto', //新建模板 时段/清洁灯关灯时间 一开始是全夜灯 默认auto
    change_timeparam_clear_lamp_turnoff:'',// 切换模板 时段/清洁灯关灯时间
    sun_on_disable:true,//模板详情 日出调整量是否可用 全夜灯半夜灯可用 时段等清洁灯不可用  
    sun_off_disable:true,//模板详情 日落调整量是否可用
    //new_sun_onoff_disable:true//新建模板 日落日出调整量是否可用 全夜灯半夜灯可用 时段等清洁灯不可用  
    new_sun_on_disable:true, //新建模板 日出调整量 是否可用 
    new_sun_off_disable:true, //新建模板 日落调整量 是否可用
    change_sun_on_disable:true, //切换模板 日出调整量 是否可用 
    change_sun_off_disable:true, //切换模板 日落调整量 是否可用
   
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    // var idx = options.idx
    // var ob = wx.getStorageSync('area' + idx)
    // wx.setNavigationBarTitle({
    //   title: ob.name,
    // })
    // var array = ob.array
    // this.setData({ items: array })

    var that = this  
    let mid = options.mid //比如这个指测试区域2 沛县 无锡测试的区域mid 就是改branch的departmentID
    let district = options.district
    let id = options.id  //上一次的id 用于loadTree 下一层的submid 10000001
    //let submid = //这个指上面mid下一层的mid  比如无锡测试下面的各个支路 测试9 测试12 测试11...

    that.setData({    
      mid:mid,
      district:district,
      id:id
    })

    wx.setNavigationBarTitle({
      title: district
    })

    wx.request({
      url: app.globalData.url + 'loadTree',
      data:{
        id:id
      },
      method: 'POST',
      header: header,
      success: function (res) {    
        let  data = JSON.parse(res.data.data)       
        that.setData({
          district_loadTree_data:data
        })
        // if (data.length != 0) {
          //这边数据需要重新组织 [{"attributes":{mid: 83, type: 1},id: 200000083,state: "closed",text: "测试1"},{"attributes":{"mid":44,"type":0},"id":100000044,"text":"沛县","state":"closed","iconCls":"area_img"},{"attributes":{"mid":45,"type":0},"id":100000045,"text":"测试","state":"closed","iconCls":"area_img"},{"attributes":{"mid":46,"type":0},"id":100000046,"t...}]
          //这个是看 mid 和 id的 id用于loadTree
          //that.optionList(data)
      //   } else if(res.errMsg != "request:ok"){
      //     wx.showModal({
      //       title: '提示',
      //       content: res.errMsg,
      //       showCancel: false
      //     })
      //   }
      }
    })   
    //var array = ob.array
    //this.setData({ items: array, idx: idx })

    wx.request({
      url:app.globalData.url+'FindAllBranchDeviceInDepartment',
      type:"post",
      header:header,
      data:{
        departmentID:mid
      },
      success:res=>{
          //一个分支的输出{"result":"{\"0025015F\":{\"autoUnusual\":1,\"online\":true,\"dname\":\"沛龙大道（三里村）\",\"gname\":\"沛龙大道(三里村)\",\"branch\":[{\"port\":\"0\",\"switch\":false},{\"port\":\"1\",\"switch\":false},{\"port\":\"2\",\"switch\":false},{\"port\":\"3\",\"switch\":false},{\"port\":\"4\",\"switch\":false}]},\"002502AA\":{\"autoUnusual\":1,\"online\":true,\"dname\":\"经四路北段\",\"gname\":\"经四路北段\",\"branch\":[{\"port\":\"0\",\"switch\":false},{\"port\":\"1\",\"switch\":false},{\"port\":\"2\",\"switch\":false}]},\"0025015E\":{\"autoUnusual\":1,\"online\":true,\"dname\":\"沛龙大道西段\",\"gname\":\"沛龙大道西段\",\"branch\":[{\"port\":\"0\",\"switch\":false},{\"port\":\"1\",\"switch\":false},{\"port\":\"2\",\"switch\":false},{\"port\":\"3\",\"switch\":false},{\"port\":\"4\",\"switch\":false}]},\"0025015C\":{\"autoUnusual\":1,\"online\":true,\"dname\":\"龙固大堤\",\"gname\":\"龙固大堤\",\"branch\":[{\"port\":\"0\",\"switch\":false},{\"port\":\"1\",\"switch\":false},{\"port\":\"2\",\"switch\":false},{\"port\":\"3\",\"switch\":false},{\"port\":\"4\",\"switch\":false}]},\"0025015A\":{\"autoUnusual\":1,\"online\":true,\"dname\":\"四海停车场\",\"gname\":\"四海停车场\",\"branch\":[{\"port\":\"0\",\"switch\":false},{\"port\":\"1\",\"switch\":false},{\"port\":\"2\",\"switch\":false},{\"port\":\"3\",\"switch\":false},{\"port\":\"4\",\"switch\":false}]},\"0025016B\":{\"autoUnusual\":1,\"online\":true,\"dname\":\"沛龙大道（龙固小加油站）\",\"gname\":\"沛龙大道（龙固小加油站）\",\"branch\":[{\"port\":\"0\",\"switch\":false},{\"port\":\"1\",\"switch\":false},{\"port\":\"2\",\"switch\":false},{\"port\":\"3\",\"switch\":false},{\"port\":\"4\",\"switch\":false}]},\"00250160\":{\"autoUnusual\":1,\"online\":true,\"dname\":\"龙固镇委\",\"gname\":\"龙固镇委\",\"branch\":[{\"port\":\"0\",\"switch\":false},{\"port\":\"1\",\"switch\":false},{\"port\":\"2\",\"switch\":false},{\"port\":\"3\",\"switch\":false},{\"port\":\"4\",\"switch\":false}]},\"002502A9\":{\"autoUnusual\":1,\"online\":true,\"dname\":\"经四路南段\",\"gname\":\"经四路南段\",\"branch\":[{\"port\":\"0\",\"switch\":false},{\"port\":\"1\",\"switch\":false},{\"port\":\"2\",\"switch\":false}]},\"002502A4\":{\"autoUnusual\":1,\"online\":true,\"dname\":\"龙固工业区\",\"gname\":\"龙固工业区\",\"branch\":[{\"port\":\"0\",\"switch\":false},{\"port\":\"1\",\"switch\":false},{\"port\":\"2\",\"switch\":false},{\"port\":\"3\",\"switch\":false},{\"port\":\"4\",\"switch\":false}]}}"}
          //这个主要是看分支详情的
          //另一个分支测试区域2的输出 {"result":"{\"002501B1\":{\"autoUnusual\":0,\"online\":false,\"dname\":\"本地测试\",\"gname\":\"测试路段\",\"branch\":[{\"port\":\"1\",\"switch\":false},{\"port\":\"0\",\"switch\":true}]}}"} 
          let res_json = res.data.result    
          let result = JSON.parse(res_json)
           
          // let devNoStrArr = []
          // let devNoStr = ""
          
          let dataArray = []

          //{AREANAME: "沛龙大道(三里村)",DEPTNAME: "沛县龙固镇",ID: 1526,IS_ONLINE: 1,POINT_NO: 4,SWITCH_STATUS: ["0", "0", "0", "0"],TERMINAL_ADDRESS:"0025015F"}
          if(result != {}){
            //取消按钮 无需组织设备号         
            for (var val in result) {
              let templateJSON = {AREANAME: "",DEPTNAME: "",ID: "",IS_ONLINE: "",POINT_NO: "",SWITCH_STATUS: [],TERMINAL_ADDRESS:"", radioStatus:false} //radioStatus 就是前面那个单选框的状态
              templateJSON.AREANAME = result[val].gname
                      
              that.data.district_loadTree_data.forEach(function(item, index){
                  if(item.text == templateJSON.AREANAME){
                      templateJSON.mid = item.attributes.mid
                      return false
                  }
              })            

              templateJSON.DEPTNAME = district
              // templateJSON.ID =  
              templateJSON.IS_ONLINE = result[val].online?1:0
              templateJSON.POINT_NO = result[val].branch.length

              templateJSON.SWITCH_STATUS = ['--', '--', '--', '--']
              for(let i=0;i<4;i++){
                if(result[val].branch[i] != undefined){
                  templateJSON.SWITCH_STATUS[i] = result[val].branch[i].switch ? "1":"0"
                }              
              }                 
              
              //templateJSON.TERMINAL_ADDRESS = val
              templateJSON.TERMINAL_ADDRESS = result[val].mac

              //后加的，用于页面的上的switch状态
              if(templateJSON.SWITCH_STATUS.indexOf("0")!=-1){
                templateJSON.checkStatus = false
              }else{
                templateJSON.checkStatus = true
              }

              dataArray.push(templateJSON);            
                      
              // if(result[val].online === true){
              //   devNoStrArr.push(val); //val 就是 \"002502A9\" 这些
              // } 
            }  
          }
          //console.log(dataArray, "dataArray")       

        // [{AREANAME: "测试9",DEPTNAME: "无锡测试",ID: "",IS_ONLINE: 1,POINT_NO: 4, SWITCH_STATUS: ["1","1", "1",1"], length: 4, TERMINAL_ADDRESS: "002500D5", checkStatus: true, mid: 91},{},{},{}]

          that.setData(
            {items: dataArray}
          )

          timer = setInterval(function () { 
            that.reloadData()
          },10000)
        }
      })
  },

  switchLight:function(e){
    var that = this
    wx.showLoading({
      title: '请稍等...',
    })
    //console.log(e, "switchLight e")
    //值是{currentTarget:dataset: {idx: "002500D5"},id: "",offsetLeft: 204,offsetTop: 55},detail: {value: true},mark: {},mut: false,dataset: {idx: "002500D5"},id: "",offsetLeft: 204,offsetTop: 55},timeStamp: 7007,type: "change"}
    if(e.detail.value){
      //全开
      wx.request({
        header:header,
        url: app.globalData.url+"OpenBranchAll",
        type:"post",
        data:{
          devNoList:e.currentTarget.dataset.idx
        },
        success:res=>{
          wx.hideLoading()          
          //console.log(res.data.error == 0, "res.data.error == 0")
          if(res.data.error == 0){
            wx.showToast({
              title: '全开操作成功',
              icon: 'success',
              duration: 2000
            })
            setTimeout(function () {              
              that.reloadData()
              //需不断调用的操作
            }, 2000)
           
          }
          if(res.data.error == -1){
            wx.showToast({
              title: '全开操作失败',
              icon: 'error',
              duration: 2000
            })
          }                
        }
      })
    }
    if(!e.detail.value){
      //全关
      wx.request({
        header:header,
        url: app.globalData.url+"CloseBranchAll",
        data:{
          devNoList:e.currentTarget.dataset.idx
        },
        success:res=>{
          wx.hideLoading()
          //console.log(res.data.error == 0, "res.data.error == 0")
          if(res.data.error == 0){
            wx.showToast({
              title: '全关操作成功',
              icon: 'success',
              duration: 2000
            })

            setTimeout(function () { 
            that.reloadData()
            },2000)
          }
          if(res.data.error == -1){
            wx.showToast({
              title: '全关操作失败',
              icon: 'error',
              duration: 2000
            })
          }
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
    //ModalGroup

    wx.request({
      url: app.globalData.url + 'GetModalGroup',
      data:{
        userid:app.globalData.userid
      },
      method: 'POST',
      header: header,
      success:function(res) {          
          let tmp_modal = JSON.parse(res.data.data)
          that.setData({
            ModalGroup:tmp_modal
          })
          //console.log(tmp_modal)
          // {"data":"[{\"name\":\"默认\",\"id\":\"1\"},{\"name\":\"单灯测试\",\"id\":\"11\"},{\"name\":\"沛县单灯\",\"id\":\"12\"},{\"name\":\"无锡\",\"id\":\"14\"},{\"name\":\"测试\",\"id\":\"22\"},{\"name\":\"无锡测试\",\"id\":\"23\"},{\"name\":\"沛县开发区\",\"id\":\"24\"},{\"name\":\"邳州灯桥管理处\",\"id\":\"25\"},{\"name\":\"半夜灯\",\"id\":\"26\"},{\"name\":\"沛县杨屯\",\"id\":\"27\"},{\"name\":\"沛县路灯\",\"id\":\"28\"},{\"name\":\"沛县亮化\",\"id\":\"30\"},{\"name\":\"模特艺术学校\",\"id\":\"31\"},{\"name\":\"徐州铜山\",\"id\":\"32\"},{\"name\":\"徐州经济开发区\",\"id\":\"33\"},{\"name\":\"明远测试\",\"id\":\"34\"},{\"name\":\"江阴\",\"id\":\"35\"},{\"name\":\"徐州照明管理处\",\"id\":\"36\"},{\"name\":\"两点关灯\",\"id\":\"37\"},{\"name\":\"半夜灯2\",\"id\":\"38\"}]"}
        
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    //console.log("clearInterval(timer) already")
    clearInterval(timer)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //console.log("clearInterval(timer) already")
    clearInterval(timer)
  },

  bindHalfLightOff: function (e) {
    this.setData({
      halfLightOff: e.detail.value
    })
  },
  bindCleanLightOn: function (e) {
    this.setData({
      cleanLightOn: e.detail.value
    })
  },
  bindBatchChoose: function (e) {
    var items = e.detail.value
    var temp = []
    var types = this.data.branchTypes
    if (items.length > 0) {
      if (items.indexOf("1") >= 0) {
        temp.push("1")
        for (var i = 0; i < types.length; i++) {
          if (i > 0) types[i].dis = true
        }
      } else {
        temp = items
        var types = types
        for (var i = 0; i < types.length; i++) {
          if (i > 0) types[i].dis = false
          else types[i].dis = true
        }
      }
    } else {
      for (var i = 0; i < types.length; i++) {
        types[i].dis = false
      }
    }
   
    this.setData({ branch: temp, branchTypes: types })
  },
  showSetup: function () {
    var that = this
    var cho = this.data.choItem
    //console.log(cho, "cho")   
    //{AREANAME: "测试9",DEPTNAME: "无锡测试",ID: "",IS_ONLINE: 1,POINT_NO: 4,SWITCH_STATUS:["0", "0", "0", "0"],TERMINAL_ADDRESS: "002500D5",checkStatus: ,mid: 91} 
    if (JSON.stringify(cho) == "{}") {
      wx.showModal({ title: '提示', content: "请选择设置终端号", showCancel: false })
      that.setData({
        firstsetupflag:true
      })
      return
    } else if (cho.IS_ONLINE == 0) {
      wx.showModal({ title: '提示', content: "离线状态不能操作", showCancel: false })
      that.setData({
        firstsetupflag:true
      })
      return
    }  
    
    if(cho.mid == undefined){
       return
    }

    //step1 根据mid 请求findbranchall 获取开关灯时间 以及lightType
    wx.request({
      type:"post",
      url: app.globalData.url+"FindAllBranch",
      header:header,
      data:{
        groupID: cho.mid, //这个是本支路的mid，而 that.data.mid是这层支路所属的区域的mid
        skip: -1
      },
      success:res=>{
        //console.log(res)
        let data = JSON.parse(res.data.data)
        //[{"turnOfftime":"16:47:00","devNo":"002502A701","groupID":"83","modalID":"57","Latitude":"31.68096","gname":"测试1","devName":"测试1设备","Longitude":"120.29834","controlNo":"002502A7","Name":"第一支路","autoUnusual":"1","modalname":"时段灯","id":"36","dname":"无锡测试","turnOntime":"16:44:00","info":"{"Auto":true,"devType":101,"sunrise":0,"OnLine":true,"devNo":"002502A701","sunset":0,"FirstSwitch":true,"FirstTurnOffTime":"16:47:00","interval":0,"FirstTurnOnTime":"16:44:00","DevCurrentTime":"2021-07-27 15:00:30","lightType":3}"},
        
        // {"turnOfftime":"16:47:00","devNo":"002502A702","groupID":"83","modalID":"57","Latitude":"31.68096","gname":"测试1","devName":"测试1设备","Longitude":"120.29834","controlNo":"002502A7","Name":"第二支路","autoUnusual":"1","modalname":"时段灯","id":"37","dname":"无锡测试","turnOntime":"16:44:00","info":"{"Auto":true,"devType":101,"sunrise":0,"OnLine":true,"devNo":"002502A702","sunset":0,"FirstSwitch":true,"FirstTurnOffTime":"16:47:00","interval":0,"FirstTurnOnTime":"16:44:00","DevCurrentTime":"2021-07-27 15:00:30","lightType":3}"},
        
        // {"turnOfftime":"16:47:00","devNo":"002502A703","groupID":"83","modalID":"57","Latitude":"31.68096","gname":"测试1","devName":"测试1设备","Longitude":"120.29834","controlNo":"002502A7","Name":"第三支路","autoUnusual":"1","modalname":"时段灯","id":"38","dname":"无锡测试","turnOntime":"16:44:00","info":"{"Auto":true,"devType":101,"sunrise":0,"OnLine":true,"devNo":"002502A703","sunset":0,"FirstSwitch":true,"FirstTurnOffTime":"16:47:00","interval":0,"FirstTurnOnTime":"16:44:00","DevCurrentTime":"2021-07-27 15:00:30","lightType":3}"},
        
        // {"turnOfftime":"16:47:00","devNo":"002502A704","groupID":"83","modalID":"57","Latitude":"31.68096","gname":"测试1","devName":"测试1设备","Longitude":"120.29834","controlNo":"002502A7","Name":"第四支路","autoUnusual":"1","modalname":"时段灯","id":"39","dname":"无锡测试","turnOntime":"16:44:00","info":"{"Auto":true,"devType":101,"sunrise":0,"OnLine":true,"devNo":"002502A704","sunset":0,"FirstSwitch":true,"FirstTurnOffTime":"16:47:00","interval":0,"FirstTurnOnTime":"16:44:00","DevCurrentTime":"2021-07-27 15:00:30","lightType":3}"}]
        var result_array = []
        // data.forEach(function(item, index){
        //   let tmp_json = {}
        //   tmp_json.name = item.name
        //   tmp_json.turnOfftime = item.info.FirstTurnOffTime
        //   tmp_json.FirstTurnOnTime = item.info.FirstTurnOnTime
        //   tmp_json.lightType = item.info.lightType
        //   tmp_json.modalID= item.modalID
        //   result_array.push(tmp_json)
        // })

        var modalID = data[0].modalID
        // result_array.forEach(function(item2, index2){
        //   wx.request({
        //     url: app.globalData.url+"FindTimeModal",
        //     type:"post",
        //     header:header,
        //     data:{
        //       modalId:item2.modalID
        //     },
        //     success:function(res){
        //       console.log(res, "modalID")
        //     }            
        //   })
        // })
        wx.request({
          url: app.globalData.url+"FindTimeModal",
          type:"post",
          header:header,
          data:{
            modalId:modalID
          },
          success:function(res){
            //console.log(res, "modalID")
            //console.log(res.data, "res.data")
            let data = res.data
           
            //{name: "时段灯" ,turnOff: "16:47:00" ,turnOffChange: "0" ,turnOn: "16:44:00" .turnOnChange: "0"}
            that.setData({
              setupflag: false, 
              ligthTypeStr:data.name, 
              halfLightOff:data.turnOff, 
              cleanLightOn:data.turnOn
            })
          }            
        })
      }
    })
    // var types = [{ name: '一支路', value: 2 }, { name: '二支路', value: 3 }
    //   , { name: '三支路', value: 4 }, { name: '四支路', value: 5 }]
    // var result = [{ name: '总路', value: 1 }]
    // var switchs = cho.SWITCH_STATUS
    // for (var i = 0; i < switchs.length; i++) {
    //   if (switchs[i] != "--") {
    //     result.push(types[i])
    //   }
    // }
    // this.setData({ setupflag: false, branchTypes: result })
  },
  edit_terminal:function(){
     var that = this
    var cho = this.data.choItem

    var isReturn = true //根据当前有没有勾选状态 决定点击终端终端设置弹不弹出对话框

    //首先界面上要有选中的 设备 判断是否有一个checkbox是选中的
    // var cur_items = that.data.items

    // cur_items.forEach(function(item, index){
    //   if(item.radioStatus === true){
    //     isReturn = false  //有勾选 不返回 要弹出 对话框
    //     return false 
    //   }
    // })

    // if(isReturn){
    //   wx.showModal({ title: '提示', content: "请选择设置终端号", showCancel: false })
    //   return
    // }

    if (JSON.stringify(cho) == "{}") {
      wx.showModal({ title: '提示', content: "请选择设置终端号", showCancel: false })
      return
    } else if (cho.IS_ONLINE == 0) {
      wx.showModal({ title: '提示', content: "离线状态不能操作", showCancel: false })
      return
    }   

  

    that.setData({
      firstsetupflag:false
    });

    that.newshowSetup()  
  },
  newshowSetup:function(){
    var that = this
    var cho = that.data.choItem
    //console.log(cho, "cho")   
    //{AREANAME: "测试9",DEPTNAME: "无锡测试",ID: "",IS_ONLINE: 1,POINT_NO: 4,SWITCH_STATUS:["0", "0", "0", "0"],TERMINAL_ADDRESS: "002500D5",checkStatus: ,mid: 91} 
    if (JSON.stringify(cho) == "{}") {
      wx.showModal({ title: '提示', content: "请选择设置终端号", showCancel: false })
      that.setData({
        firstsetupflag:true
      })
      return
    } else if (cho.IS_ONLINE == 0) {
      wx.showModal({ title: '提示', content: "离线状态不能操作", showCancel: false })
      that.setData({
        firstsetupflag:true
      })
      return
    }     
   
    if(cho.mid == undefined){
      console.log(JSON.stringify(cho), "newshowsetup mid undefined")
      return
    }

    //step1 根据自己的mid 请求findbranchall 获取开关灯时间 以及lightType
    wx.request({
      type:"post",
      url: app.globalData.url+"FindAllBranch",
      header:header,
      data:{
        groupID: cho.mid, //这个是本支路的mid，而 that.data.mid是这层支路所属的区域的mid
        skip: -1
      },
      success:res=>{
        //console.log(res)
        let data = JSON.parse(res.data.data)
        //[{"turnOfftime":"16:47:00","devNo":"002502A701","groupID":"83","modalID":"57","Latitude":"31.68096","gname":"测试1","devName":"测试1设备","Longitude":"120.29834","controlNo":"002502A7","Name":"第一支路","autoUnusual":"1","modalname":"时段灯","id":"36","dname":"无锡测试","turnOntime":"16:44:00","info":"{"Auto":true,"devType":101,"sunrise":0,"OnLine":true,"devNo":"002502A701","sunset":0,"FirstSwitch":true,"FirstTurnOffTime":"16:47:00","interval":0,"FirstTurnOnTime":"16:44:00","DevCurrentTime":"2021-07-27 15:00:30","lightType":3}"},
        
        // {"turnOfftime":"16:47:00","devNo":"002502A702","groupID":"83","modalID":"57","Latitude":"31.68096","gname":"测试1","devName":"测试1设备","Longitude":"120.29834","controlNo":"002502A7","Name":"第二支路","autoUnusual":"1","modalname":"时段灯","id":"37","dname":"无锡测试","turnOntime":"16:44:00","info":"{"Auto":true,"devType":101,"sunrise":0,"OnLine":true,"devNo":"002502A702","sunset":0,"FirstSwitch":true,"FirstTurnOffTime":"16:47:00","interval":0,"FirstTurnOnTime":"16:44:00","DevCurrentTime":"2021-07-27 15:00:30","lightType":3}"},
        
        // {"turnOfftime":"16:47:00","devNo":"002502A703","groupID":"83","modalID":"57","Latitude":"31.68096","gname":"测试1","devName":"测试1设备","Longitude":"120.29834","controlNo":"002502A7","Name":"第三支路","autoUnusual":"1","modalname":"时段灯","id":"38","dname":"无锡测试","turnOntime":"16:44:00","info":"{"Auto":true,"devType":101,"sunrise":0,"OnLine":true,"devNo":"002502A703","sunset":0,"FirstSwitch":true,"FirstTurnOffTime":"16:47:00","interval":0,"FirstTurnOnTime":"16:44:00","DevCurrentTime":"2021-07-27 15:00:30","lightType":3}"},
        
        // {"turnOfftime":"16:47:00","devNo":"002502A704","groupID":"83","modalID":"57","Latitude":"31.68096","gname":"测试1","devName":"测试1设备","Longitude":"120.29834","controlNo":"002502A7","Name":"第四支路","autoUnusual":"1","modalname":"时段灯","id":"39","dname":"无锡测试","turnOntime":"16:44:00","info":"{"Auto":true,"devType":101,"sunrise":0,"OnLine":true,"devNo":"002502A704","sunset":0,"FirstSwitch":true,"FirstTurnOffTime":"16:47:00","interval":0,"FirstTurnOnTime":"16:44:00","DevCurrentTime":"2021-07-27 15:00:30","lightType":3}"}]
        var result_array = []
        // data.forEach(function(item, index){
        //   let tmp_json = {}
        //   tmp_json.name = item.name
        //   tmp_json.turnOfftime = item.info.FirstTurnOffTime
        //   tmp_json.FirstTurnOnTime = item.info.FirstTurnOnTime
        //   tmp_json.lightType = item.info.lightType
        //   tmp_json.modalID= item.modalID
        //   result_array.push(tmp_json)
        // })

        var modalID = data[0].modalID
        that.setData({
          ModalGroupName:data[0].dname  //模板组名称 比如无锡测试
        })
       
        wx.request({
          url: app.globalData.url+"FindTimeModal",
          type:"post",
          header:header,
          data:{
            modalId:modalID
          },
          success:function(res){
            //console.log(res, "modalID")
            //console.log(res.data, "res.data")
            let data = res.data
           
            //{name: "时段灯" ,turnOff: "16:47:00" ,turnOffChange: "0" ,turnOn: "16:44:00" .turnOnChange: "0"}
            that.setData({
              // setupflag: false, 
              ligthTypeStr:data.name,  //当前模板的名称
              halfLightOff:data.turnOff, 
              cleanLightOn:data.turnOn
            })

            //step1 从modalGroup里面 根据 modalGroup找到是哪个模板组 找到改模板组的id 即对应吓一跳协议的参数gid
            let tmp_modalGroup = that.data.ModalGroup
            let tmp_modalGroupName = that.data.ModalGroupName
            let findModalGroupName = false

            tmp_modalGroup.forEach(function(item, index) {
              if(item.name == tmp_modalGroupName){
                that.setData({
                  cur_group_id:item.id
                })
                findModalGroupName = true
                return false;
              }              
            })

            //说明在已知的模板组里面没有到该模板 比如沛县龙固镇         
            if(findModalGroupName === false){
              wx.showToast({
                title: '抱歉,暂未找到该模板无法修改！',
                icon:'success',
                duration:2000
              }) 
              
              that.setData({
                setupflag:true
              })
              return
            }
          
            //step2 开始获取模板用于显示
            wx.request({
              header:header,
              type:"post",
              url: app.globalData.url+'GetLightModal',
              data:{
                userid:app.globalData.userid,
                gid:that.data.cur_group_id
              },
              success:function(res) {
                //"[{\"turnOff\":\"auto\",\"turnOffChange\":\"1\",\"gid\":\"23\",\"modalType\":\"0\",\"turnOn\":\"auto\",\"name\":\"全夜灯\",\"id\":\"54\",\"turnOnChange\":\"1\",\"group\":\"无锡测试\"},{\"turnOff\":\"23:00:00\",\"turnOffChange\":\"0\",\"gid\":\"23\",\"modalType\":\"1\",\"turnOn\":\"auto\",\"name\":\"半夜灯\",\"id\":\"55\",\"turnOnChange\":\"-45\",\"group\":\"无锡测试\"},{\"turnOff\":\"15:35:00\",\"turnOffChange\":\"0\",\"gid\":\"23\",\"modalType\":\"3\",\"turnOn\":\"15:30:00\",\"name\":\"时段灯\",\"id\":\"57\",\"turnOnChange\":\"0\",\"group\":\"无锡测试\"}]"
                let modaldata = JSON.parse(res.data.data) 
                that.setData({
                  LightModal:modaldata
                })
                let cur_modal = []
                modaldata.forEach(function(item, index) {
                    if(item.name == that.data.ligthTypeStr){
                      cur_modal = item                          
                      that.setData({
                        LightModal_index:index, //这个时候找到具体是那个模板，以及那个模板的index
                        template_name:cur_modal.name,
                        modalGroupID:item.id,
                        timeparam_clear_lamp_turnon:item.turnOn,//时段/清洁灯开灯时间
                        timeparam_clear_lamp_turnoff:item.turnOff,//时段/清洁灯关灯时间
                        addVal: item.turnOffChange, // 日出调整量
                        subVal: item.turnOnChange, // 日落调整量
                      })
                      that.data.types.forEach(function(item2, index) {
                        if(item2.value == cur_modal.modalType){
                          that.setData({
                            types_index:index
                          })

                          //全夜灯 指定开关等时间类型 为根据设备所在经纬度自动调整
                          if(item2.value == 0 ){
                            that.setData({
                              switchTypes_index:1,  //更具设备所在经纬度自动字段
                              timeparam_clear_lamp_turnon:"auto",
                              sun_off_disable:true,  //全夜日落时间调整量可用
                              subVal: item.turnOnChange, // 日落调整量
                              switchTypes_off_index:1,
                              timeparam_clear_lamp_turnoff:"auto",
                              sun_on_disable:true, //日出时间调整量可用
                              addVal: item.turnOffChange, // 日出调整量                                 
                            })
                          }
                          //半夜灯                            
                          if(item2.value == 1){
                            that.setData({
                              switchTypes_index:1,  //更具设备所在经纬度自动字段
                              timeparam_clear_lamp_turnon:"auto",
                              sun_off_disable:true,  //全夜日落时间调整量可用
                              subVal: item.turnOnChange, // 日落调整量
                              switchTypes_off_index:0,
                              timeparam_clear_lamp_turnoff:item.turnOff,
                              sun_on_disable:false, //日出时间调整量可用
                              addVal: 0, // 日出调整量                                 
                            })    

                          }

                          //清洁灯 指定开关等时间类型 指定时间
                          if(item2.value == 2){
                            that.setData({
                              switchTypes_index:0,  //开灯时间类型 指定时间
                              timeparam_clear_lamp_turnon:item.turnOn,                                
                              sun_off_disable:true,  //全夜日落时间调整量可用
                              subVal: item.turnOnChange, // 日落调整量

                              switchTypes_off_index:0,  //关灯时间类型 指定时间
                              timeparam_clear_lamp_turnoff:item.turnOff,
                              sun_on_disable:true, //日出时间调整量可用
                              addVal: item.turnOffChange, // 日出调整量 
                            })
                          }

                          //时段灯
                          if(item2.value == 3){
                            that.setData({
                              switchTypes_index:0,  //开灯时间类型 指定时间
                              timeparam_clear_lamp_turnon:item.turnOn,                                
                              sun_off_disable:false,  //全夜日落时间调整量可用
                              subVal: 0, // 日落调整量

                              switchTypes_off_index:0,  //关灯时间类型 指定时间
                              timeparam_clear_lamp_turnoff:item.turnOff,
                              sun_on_disable:false, //日出时间调整量可用
                              addVal: 0, // 日出调整量 
                            })
                          }

                          return false
                        }                        
                      })
                      return false
                    }                  
                })

                //console.log(that.data, "that.data")                
              }
            })  
            }                   
        }) 
      }
    })
  },
  hideSetup: function () {
    this.setData({ setupflag: true })
    this.setData({ branchTypes: [] })

    //刚添加的 这个当前模板详情页面 取消后 需要重新弹出 第一层的 显示详情 切换模板 新增模板的 弹出框
    this.setData({
      firstsetupflag:false
    })

  },

  //新建模板 取消按钮
  hideNewTemplate:function() {
    this.setData({
      firstsetupflag:false,
      newtemplateflag:true
    })
  },

  hideSetup_selectTemplate: function () {
    this.setData({ selectTemplateflag: true })
    this.setData({ branchTypes: [] })

    //刚添加的 这个当前模板详情页面 取消后 需要重新弹出 第一层的 显示详情 切换模板 新增模板的 弹出框
    this.setData({
      firstsetupflag:false
    })
  },

  curtemplate_hideSetup:function(){
    this.setData({
      firstsetupflag:true,
      setupflag: true,  //模板详细信息 弹出层
      selectTemplateflag:true,  //选择模板弹出层
      newtemplateflag:true //新建模板弹出层   
    })
  },
  radioChange: function (e) {
    this.setData({ lightType: e.detail.value })
  },

  //模板名称设置
  userNameInput:function(e) {
      let that = this
      that.setData({
        template_name:e.detail.value
      }) 
  },

  //新建模板名称设置
  newuserNameInput:function(e){
    let that = this
   
    that.setData({
      new_template_name:e.detail.value
    }) 
  },


  //日出时间调整函数
  bindInputadd: function (e) {
    let that = this
    that.setData({ addVal: e.detail.value  })
  },

  //新建模板 日出时间调整函数
  newbindInputadd: function (e) {
    let that = this
    that.setData({ new_addVal: e.detail.value  })
  },

  //日落时间调整函数
  bindInputsub: function (e) {
    let that = this
    that.setData({ subVal: e.detail.value })
  },

   //新建模板 日落时间调整函数
  newbindInputsub: function (e) {
    let that = this
    that.setData({ new_subVal: e.detail.value })
  },

  bindChoice: function (e) {
    var item = e.currentTarget.dataset.ob
    //console.log(item, "item bindChoice")
    this.setData({ choItem: item })
  },

  //查看模板 修改 提交触发事件
  bingToSetup: function (e) {
    var that = this
    var opy = e.currentTarget.dataset.opy
    var cho = that.data.choItem
    if (JSON.stringify(cho) == "{}") {
      wx.showModal({ title: '提示', content: "请选择设置终端号", showCancel: false })
      that.setData({
        firstsetupflag:true
      })
      return
    } else if (cho.IS_ONLINE == 0){
      wx.showModal({ title: '提示', content: "离线状态不能操作", showCancel: false })
      that.setData({
        firstsetupflag:true
      })
      return
    }

    let id = that.data.modalGroupID  //模板id
    //console.log(id, "id")

    let modalName = that.data.template_name //模板名称input
    //console.log(modalName, "modalName")

    //that.data.template_switch_type 
    let modalType =  that.data.types[that.data.types_index].value//开关等类型picker
    //console.log(modalType, "modalType")

    let turnOnType = that.data.switchTypes_index //开灯时间类型 input switchTypes[switchTypes_index]
    //console.log(turnOnType, "turnOnType")

    let modalTurnOn = that.data.timeparam_clear_lamp_turnon //时段/清洁灯开灯时间 picker
    //console.log(modalTurnOn, "modalTurnOn")

    let turnOnChange = that.data.subVal //日落时间调整分钟数 input
    //console.log(turnOnChange, "turnOnChange")

    let turnOffType = that.data.switchTypes_off_index //关灯时间类型 picker
    //console.log(turnOffType, "turnOffType")

    let modalTurnOff = that.data.timeparam_clear_lamp_turnoff //时段/清洁灯关灯时间
    //console.log(modalTurnOff, "modalTurnOff")

    let turnOffChange = that.data.addVal//日出时间调整
    //console.log(turnOffChange, "turnOffChange")

    wx.request({
      header:header,
      type:'post',
      url: app.globalData.url+'UpdateLightModal',
      data:{
          modalName: modalName, //模板名称
	        turnOnType: turnOnType,  
          turnOffType: turnOffType,
          modalTurnOn: modalTurnOn,
          modalTurnOff: modalTurnOff,
          turnOnChange: turnOnChange,
          turnOffChange: turnOffChange,
          userid: app.globalData.userid,
          id: id,
          modalType: modalType
      },
      success:function(res) {
        //console.log(res, "res")
        that.hideSetup()
        if(res.data.error == "0"){
          wx.showToast({
            title: '修改模板成功',
            icon:'success',
            duration:2000
          })
        }else{
          wx.showToast({
            title: '修改模板失败',
            icon:'error',
            duration:2000
          })
        }        
      }
    })   
  },

  //新建模板提交触发事件
  bingToNewTemplate:function(e) {
    var that = this
    var opy = e.currentTarget.dataset.opy
    var cho = that.data.choItem

    
    if (JSON.stringify(cho) == "{}") {
      wx.showModal({ title: '提示', content: "请选择设置终端号", showCancel: false })
      that.setData({
        firstsetupflag:true
      })
      return
    } else if (cho.IS_ONLINE == 0){
      wx.showModal({ title: '提示', content: "离线状态不能操作", showCancel: false })
      that.setData({
        firstsetupflag:true
      })
      return
    }

    let id = that.data.cur_group_id  //模板id
    //console.log(id, "id")

    let modalName = that.data.new_template_name //模板名称input
    //console.log(modalName, "modalName")

    //that.data.template_switch_type 
    let modalType =  that.data.types[that.data.new_types_index].value//开关等类型picker
    //console.log(modalType, "modalType")

    let turnOnType = that.data.new_switchTypes_index //开灯时间类型 input switchTypes[switchTypes_index]
    //console.log(turnOnType, "turnOnType")

    let modalTurnOn = that.data.new_timeparam_clear_lamp_turnon //时段/清洁灯开灯时间 picker
    //console.log(modalTurnOn, "modalTurnOn")

    let turnOnChange = that.data.new_subVal //日落时间调整分钟数 input
    //console.log(turnOnChange, "turnOnChange")

    let turnOffType = that.data.new_switchTypes_off_index //关灯时间类型 picker
    //console.log(turnOffType, "turnOffType")

    let modalTurnOff = that.data.new_timeparam_clear_lamp_turnoff //时段/清洁灯关灯时间
    //console.log(modalTurnOff, "modalTurnOff")

    let turnOffChange = that.data.new_addVal//日出时间调整
    //console.log(turnOffChange, "turnOffChange")

    wx.request({
      header:header,
      type:'post',
      url: app.globalData.url+'addLightModal',
      data:{
          modalName: modalName, //模板名称
	        turnOnType: turnOnType,  
          turnOffType: turnOffType,
          modalTurnOn: modalTurnOn,
          modalTurnOff: modalTurnOff,
          turnOnChange: turnOnChange,
          turnOffChange: turnOffChange,
          userid: app.globalData.userid,
          gid: id,
          modalType: modalType
      },
      success:function(res) {
        console.log(res, "res")
        that.hideSetup()
        if(res.data.error ===  "true"){
          wx.showToast({
            title: '新建模板成功',
            icon:'success',
            duration:2000,
            success:function(params) {
              that.hideNewTemplate()              
            }
          })
        }else{
          wx.showToast({
            title: '新建模板失败',
            icon:'error',
            duration:2000,
            success:function(params) {
              that.hideNewTemplate()              
            }
          })
        }        
      }
    })    
  },

  //选择模板提交触发事件
  bingToSetup_selectTemplate:function(e){
    var that = this
    var opy = e.currentTarget.dataset.opy
    var cho = that.data.choItem
    console.log(cho, "cho 切换模板")
    if (JSON.stringify(cho) == "{}") {
      wx.showModal({ title: '提示', content: "请选择设置终端号", showCancel: false })
      that.setData({
        firstsetupflag:true
      })
      return
    } else if (cho.IS_ONLINE == 0){
      wx.showModal({ title: '提示', content: "离线状态不能操作", showCancel: false })
      that.setData({
        firstsetupflag:true
      })
      return
    }

    let id = that.data.modalGroupID  //模板id
    //console.log(id, "id")

    //let modalName = that.data.template_name //模板名称input
    let modalName = that.data.LightModal[that.data.change_LightModal_index].name
    //console.log(modalName, "modalName")

    //that.data.template_switch_type 
    let modalType =  that.data.types[that.data.change_types_index].value//开关等类型picker
    //console.log(modalType, "modalType")

    let turnOnType = that.data.change_switchTypes_index //开灯时间类型 input switchTypes[switchTypes_index]
    //console.log(turnOnType, "turnOnType")

    let modalTurnOn = that.data.change_timeparam_clear_lamp_turnon //时段/清洁灯开灯时间 picker
    //console.log(modalTurnOn, "modalTurnOn")

    let turnOnChange = that.data.change_subVal //日落时间调整分钟数 input
    //console.log(turnOnChange, "turnOnChange")

    let turnOffType = that.data.change_switchTypes_off_index //关灯时间类型 picker
    //console.log(turnOffType, "turnOffType")

    let modalTurnOff = that.data.change_timeparam_clear_lamp_turnoff //时段/清洁灯关灯时间
    //console.log(modalTurnOff, "modalTurnOff")

    let turnOffChange = that.data.change_addVal//日出时间调整
    //console.log(turnOffChange, "turnOffChange")   

    wx.request({
      header:header,
      type:'post',
      url: app.globalData.url+'UpdateGroupTimeModal',
      data:{
          // modalName: modalName, //模板名称
	        // turnOnType: turnOnType,  
          // turnOffType: turnOffType,
          // modalTurnOn: modalTurnOn,
          // modalTurnOff: modalTurnOff,
          // turnOnChange: turnOnChange,
          // turnOffChange: turnOffChange,
          // userid: app.globalData.userid,
          // id: id,
          // modalType: modalType
          modalID:id,
          target:[{"attributes":{"mid":cho.mid,"type":1}}]  //这个mid指 测试路段 下面分支的mid 比如 测试1 测试2.。。 测试路段本身的mid是 that.data.mid
      },
      success:function(res) {
        //console.log(res, "res")
        that.hideSetup_selectTemplate()
        if(res.data.error == "0"){
          that.setData({
            ligthTypeStr:modalName //切换模板成功 记录下最新的模板名称
          });
          wx.showToast({
            title: '修改模板成功',
            icon:'success',
            duration:2000
          })
        }else{
          wx.showToast({
            title: '修改模板失败',
            icon:'error',
            duration:2000
          })
        }        
      }
    })
  },


  //选择新的模板后 下面的模板详情跟着改变的函数
  select_template_change:function(){
     let that = this;
     //let cur_template = that.data.LightModal[that.data.change_types_index]
     let cur_template = that.data.LightModal[that.data.change_LightModal_index]
    //  that.setData({  
    //   cur_LightModal:cur_template
    //  })

      let cur_modal = cur_template
      that.setData({     
        //template_name:cur_modal.name,
        modalGroupID:cur_modal.id,
        change_timeparam_clear_lamp_turnon:cur_modal.turnOn,//时段/清洁灯开灯时间
        change_timeparam_clear_lamp_turnoff:cur_modal.turnOff,//时段/清洁灯关灯时间
        change_addVal: cur_modal.turnOffChange, // 日出调整量
        change_subVal: cur_modal.turnOnChange, // 日落调整量
      })
      that.data.types.forEach(function(item2, index) {
        if(item2.value == cur_modal.modalType){
          that.setData({
            change_types_index:index
          })

          //全夜灯 指定开关等时间类型 为根据设备所在经纬度自动调整
          if(item2.value == 0){
            that.setData({
              change_switchTypes_index:1,  //更具设备所在经纬度自动字段
              change_timeparam_clear_lamp_turnon:'auto',
              change_sun_off_disable:true,  //日落时间调整量可用
              change_subVal:cur_modal.turnOnChange, // 日落调整量
              change_switchTypes_off_index:1,  //更具设备所在经纬度自动字段
              change_timeparam_clear_lamp_turnoff:'auto',
              change_sun_on_disable:true,  //日出时间调整量可用
              change_addVal: cur_modal.turnOffChange, // 日出调整量
            })
          }

          //半夜灯
          if( item2.value == 1){
            that.setData({
              change_switchTypes_index:1,  //更具设备所在经纬度自动字段
              change_timeparam_clear_lamp_turnon:'auto',
              change_sun_off_disable:true,  //日落时间调整量可用
              change_subVal:cur_modal.turnOnChange, // 日落调整量
              change_switchTypes_off_index:0,  //指定时间
              change_timeparam_clear_lamp_turnoff:cur_modal.turnOff,
              change_sun_on_disable:false,  //日出时间调整量可用
              change_addVal: 0, // 日出调整量
            })
          }

          //清洁灯 指定开关等时间类型 指定时间
          if(item2.value == 2 ){
            that.setData({
              change_switchTypes_index:0,  //指定时间
              change_timeparam_clear_lamp_turnon:cur_modal.turnOn, //情节灯开灯时间可以设置
              change_sun_off_disable:true,  //日落时间调整量可用
              change_subVal:cur_modal.turnOnChange, // 日落调整量
              change_switchTypes_off_index:0,  //指定时间
              change_timeparam_clear_lamp_turnoff:cur_modal.turnOff, //时段半夜灯关灯时间
              change_sun_on_disable:true,  //日出时间调整量可用
              change_addVal: cur_modal.turnOffChange, // 日出调整量
            })
          }

          //时段灯
          if(item2.value == 3){
            that.setData({
              change_switchTypes_index:0,  //指定时间
              change_timeparam_clear_lamp_turnon:cur_modal.turnOn, //时段/清洁灯开灯时间可以设置
              change_sun_off_disable:false,  //日落时间调整量可用
              change_subVal:0, // 日落调整量
              change_switchTypes_off_index:0,  //指定时间
              change_timeparam_clear_lamp_turnoff:cur_modal.turnOff, //时段半夜灯关灯时间
              change_sun_on_disable:false,  //日出时间调整量可用
              change_addVal: 0 // 日出调整量
            })
          }

         return false
        }                        
     })
  },

  reloadData:function(){
    var that = this

    wx.request({
      url: app.globalData.url + 'loadTree',
      data:{
        id:that.data.id
      },
      method: 'POST',
      header: header,
      success: function (res) {    
        let  data = JSON.parse(res.data.data)       
        that.setData({
          district_loadTree_data:data
        })      
      }
    })   
   
    wx.request({
      url:app.globalData.url+'FindAllBranchDeviceInDepartment',
      type:"post",
      header:header,
      data:{
        departmentID:that.data.mid
      },
      success:res=>{                  
          let res_json = res.data.result    
          let result = JSON.parse(res_json)
         
          let dataArray = []

          //{AREANAME: "沛龙大道(三里村)",DEPTNAME: "沛县龙固镇",ID: 1526,IS_ONLINE: 1,POINT_NO: 4,SWITCH_STATUS: ["0", "0", "0", "0"],TERMINAL_ADDRESS:"0025015F"}
          if(result != {}){
            //取消按钮 无需组织设备号         
            for (var val in result) {
              let templateJSON = {AREANAME: "",DEPTNAME: "",ID: "",IS_ONLINE: "",POINT_NO: "",SWITCH_STATUS: [],TERMINAL_ADDRESS:"",radioStatus:false}
              templateJSON.AREANAME = result[val].gname

               that.data.district_loadTree_data.forEach(function(item, index){
                  if(item.text == templateJSON.AREANAME){
                      templateJSON.mid = item.attributes.mid                      
                      return false
                  }
              })


              templateJSON.DEPTNAME = that.data.district
              // templateJSON.ID =  
              templateJSON.IS_ONLINE = result[val].online?1:0
              templateJSON.POINT_NO = result[val].branch.length

              templateJSON.SWITCH_STATUS = ['--', '--', '--', '--']
              for(let i=0;i<4;i++){
                if(result[val].branch[i] != undefined){
                  templateJSON.SWITCH_STATUS[i] = result[val].branch[i].switch ? "1":"0"
                }              
              }                 
              
              //templateJSON.TERMINAL_ADDRESS = val
              templateJSON.TERMINAL_ADDRESS = result[val].mac

              //后加的，用于页面的上的switch状态
              if(templateJSON.SWITCH_STATUS.indexOf("0")!=-1){
                templateJSON.checkStatus = false
              }else{
                templateJSON.checkStatus = true
              }

              dataArray.push(templateJSON);    
            }  
          }  

          that.setData(
            {items: dataArray}
          )
        }
      })
  },
  //选择模板的选择器的绑定函数
  bindPickerChangeLightModal:function(e){
    let that = this    
    that.setData({
      change_LightModal_index:parseInt(e.detail.value)
    })   
    
    //选择模板 
    that.select_template_change()
  },

  //开关等类型 查看详情
  bindPickerChangeSwitchType:function(e) {
    let that = this
    //console.log(e, "bindPickerChangeSwitchType e")
    that.setData({
      types_index:parseInt(e.detail.value)
    })    

    let types_value = parseInt(that.data.types[that.data.types_index].value)
    //console.log(types_value, "types_values")
  
       //全夜灯和半夜灯 指定开关等时间类型 为根据设备所在经纬度自动调整
       if(types_value== 0){
        that.setData({
          switchTypes_index:1,  //更具设备所在经纬度自动字段       
          timeparam_clear_lamp_turnon:"auto",          
          sun_off_disable:true,
          subVal:0,
          switchTypes_off_index:1,
          timeparam_clear_lamp_turnoff:"auto",
          sun_on_disable:true,  
          addVal:0
        })
      }

      //半夜灯
      if( types_value == 1){
        that.setData({
          switchTypes_index:1,  //更具设备所在经纬度自动字段       
          timeparam_clear_lamp_turnon:"auto",          
          sun_off_disable:true,
          subVal:0,
          switchTypes_off_index:0,
          timeparam_clear_lamp_turnoff:"",
          sun_on_disable:false,  
          addVal:0
        })
      }

      //清洁灯 指定开关等时间类型 指定时间
      if(types_value == 2){
        that.setData({
          switchTypes_index:0,  //更具设备所在经纬度自动字段       
          timeparam_clear_lamp_turnon:"",          
          sun_off_disable:true,
          subVal:0,
          switchTypes_off_index:0,
          timeparam_clear_lamp_turnoff:"",
          sun_on_disable:true,  
          addVal:0
        })
      }    

      //时段灯
      if(types_value == 3){
        that.setData({
          switchTypes_index:0,  //更具设备所在经纬度自动字段       
          timeparam_clear_lamp_turnon:"",          
          sun_off_disable:false,
          subVal:0,
          switchTypes_off_index:0,
          timeparam_clear_lamp_turnoff:"",
          sun_on_disable:false,  
          addVal:0
        })

      }
  },

  //新增模板 开关灯类型
  newbindPickerChangeSwitchType:function(e) {
    let that = this
    //console.log(e, "bindPickerChangeSwitchType e")
    that.setData({
      new_types_index:parseInt(e.detail.value)
    })    

    let types_value = parseInt(that.data.types[that.data.new_types_index].value)   
  
    //全夜灯指定开关等时间类型 为根据设备所在经纬度自动调整
    if(types_value== 0 ){
      that.setData({
        new_switchTypes_index:1,  //更具设备所在经纬度自动字段         
        new_timeparam_clear_lamp_turnon:"auto",
        new_sun_off_disable:true, //全夜灯日落时间调整量可用
        new_subVal:0,
        new_switchTypes_off_index:1,  //更具设备所在经纬度自动字段
        new_timeparam_clear_lamp_turnoff:"auto",
        new_sun_on_disable:true,  //全夜灯日出时间调整量可用
        new_addVal:0        
      })
    }

    //半夜灯 关灯事件类型 指定事件
    if(types_value == 1){        
      that.setData({
        new_switchTypes_index:1,  //更具设备所在经纬度自动字段
        new_timeparam_clear_lamp_turnon:"auto",
        new_sun_off_disable:true, //全夜灯日落时间调整量可用
        new_subVal:0,

        new_switchTypes_off_index:0,  //关灯时间类型 指定时间
        new_timeparam_clear_lamp_turnoff:"",  //时段/清洁灯时间关灯时间
        new_sun_on_disable:false,  //半夜灯 不可用
        new_addVal:0,
      })
    }

    //清洁灯 指定开关等时间类型 指定时间
    if(types_value == 2 ){
      that.setData({
        new_switchTypes_index:0,  //指定时间      
        new_timeparam_clear_lamp_turnon:'',
        new_sun_off_disable:true, //清洁灯日落时间调整量可用
        new_subVal:0,

        new_switchTypes_off_index:0,  //指定时间  
        new_timeparam_clear_lamp_turnoff:'',
        new_sun_on_disable:true,  //清洁灯 日出时间调整量可用
        new_addVal:0,
      })
    }

    //时段灯
    if(types_value == 3){
      that.setData({
        new_switchTypes_index:0,  //指定时间      
        new_timeparam_clear_lamp_turnon:'',
        new_sun_off_disable:false, //清洁灯日落时间调整量可用
        new_subVal:0,

        new_switchTypes_off_index:0,  //指定时间   
        new_timeparam_clear_lamp_turnoff:'',
        new_sun_on_disable:false,  //时段/清洁灯 日出日落时间调整量不可用
        new_addVal:0,
      })
    }    
  },

  //开灯时间类型 查看详情
  bindPickerChangeTurnOnType:function(e) {
    let that = this
    that.setData({
      switchTypes_index:parseInt(e.detail.value)
    })
  },

  //开灯时间类型 切换模板
  changebindPickerChangeTurnOnType:function(e) {
    let that = this
    that.setData({
      change_switchTypes_index:parseInt(e.detail.value)
    })
  },


  //新建模板 开灯时间类型
  newbindPickerChangeTurnOnType:function(e){
    let that = this
    that.setData({
      new_switchTypes_index:parseInt(e.detail.value)
    })
  },

  //新建模板 关灯时间类型
  newbindPickerChangeTurnOffType:function(e){
    let that = this
    that.setData({
      new_switchTypes_off_index:parseInt(e.detail.value)
    })
  },

  //模板详情 关灯时间类型
  bindPickerChangeTurnOffType:function(e){
    let that = this
    that.setData({
      switchTypes_off_index:parseInt(e.detail.value)
    })
  },

  //时段/清洁灯开灯时间
  bindTimeChangeTurnOn:function(e) {
    let that = this
    //console.log('picker发送选择改变，携带值为', e.detail.value)
    that.setData({
      timeparam_clear_lamp_turnon: e.detail.value+":00"
    })
  },

  //新建模板 时段/清洁灯开灯时间
  newbindTimeChangeTurnOn:function(e) {
    let that = this
    //console.log('picker发送选择改变，携带值为', e.detail.value)
    that.setData({
      new_timeparam_clear_lamp_turnon: e.detail.value+":00"
    })
  },


  //时段/清洁灯关灯时间
  bindTimeChangeTurnOff:function(e) {
    let that = this
    //console.log('picker发送选择改变，携带值为', e.detail.value)
    that.setData({
      timeparam_clear_lamp_turnoff: e.detail.value+":00"
    })
  },

  //新建模板 时段/清洁灯关灯时间
  newbindTimeChangeTurnOff:function(e) {
    let that = this
    that.setData({
      new_timeparam_clear_lamp_turnoff: e.detail.value+":00"
    })
  },

  //显示当前模板详情
  showTemplateDetail:function(e){
    let that = this;
    that.setData({
      firstsetupflag:true,
      setupflag:false
    })
    that.newshowSetup()
  },

  //点击选择其他模板
  selectTemplate:function(e){
    let that = this

    that.setData({
      selectTemplateflag:false
    })  

    //获得当前所用模板
    var cho = this.data.choItem   

    //step1 根据自己的mid 请求findbranchall 获取开关灯时间 以及lightType
    wx.request({
      type:"post",
      url: app.globalData.url+"FindAllBranch",
      header:header,
      data:{
        groupID: cho.mid, //这个是本支路的mid，而 that.data.mid是这层支路所属的区域的mid
        skip: -1
      },
      success:res=>{
        //console.log(res)
        let data = JSON.parse(res.data.data)
        //[{"turnOfftime":"16:47:00","devNo":"002502A701","groupID":"83","modalID":"57","Latitude":"31.68096","gname":"测试1","devName":"测试1设备","Longitude":"120.29834","controlNo":"002502A7","Name":"第一支路","autoUnusual":"1","modalname":"时段灯","id":"36","dname":"无锡测试","turnOntime":"16:44:00","info":"{"Auto":true,"devType":101,"sunrise":0,"OnLine":true,"devNo":"002502A701","sunset":0,"FirstSwitch":true,"FirstTurnOffTime":"16:47:00","interval":0,"FirstTurnOnTime":"16:44:00","DevCurrentTime":"2021-07-27 15:00:30","lightType":3}"},
        
        // {"turnOfftime":"16:47:00","devNo":"002502A702","groupID":"83","modalID":"57","Latitude":"31.68096","gname":"测试1","devName":"测试1设备","Longitude":"120.29834","controlNo":"002502A7","Name":"第二支路","autoUnusual":"1","modalname":"时段灯","id":"37","dname":"无锡测试","turnOntime":"16:44:00","info":"{"Auto":true,"devType":101,"sunrise":0,"OnLine":true,"devNo":"002502A702","sunset":0,"FirstSwitch":true,"FirstTurnOffTime":"16:47:00","interval":0,"FirstTurnOnTime":"16:44:00","DevCurrentTime":"2021-07-27 15:00:30","lightType":3}"},
        
        // {"turnOfftime":"16:47:00","devNo":"002502A703","groupID":"83","modalID":"57","Latitude":"31.68096","gname":"测试1","devName":"测试1设备","Longitude":"120.29834","controlNo":"002502A7","Name":"第三支路","autoUnusual":"1","modalname":"时段灯","id":"38","dname":"无锡测试","turnOntime":"16:44:00","info":"{"Auto":true,"devType":101,"sunrise":0,"OnLine":true,"devNo":"002502A703","sunset":0,"FirstSwitch":true,"FirstTurnOffTime":"16:47:00","interval":0,"FirstTurnOnTime":"16:44:00","DevCurrentTime":"2021-07-27 15:00:30","lightType":3}"},
        
        // {"turnOfftime":"16:47:00","devNo":"002502A704","groupID":"83","modalID":"57","Latitude":"31.68096","gname":"测试1","devName":"测试1设备","Longitude":"120.29834","controlNo":"002502A7","Name":"第四支路","autoUnusual":"1","modalname":"时段灯","id":"39","dname":"无锡测试","turnOntime":"16:44:00","info":"{"Auto":true,"devType":101,"sunrise":0,"OnLine":true,"devNo":"002502A704","sunset":0,"FirstSwitch":true,"FirstTurnOffTime":"16:47:00","interval":0,"FirstTurnOnTime":"16:44:00","DevCurrentTime":"2021-07-27 15:00:30","lightType":3}"}]
        var result_array = []      

        var modalID = data[0].modalID
        that.setData({
          ModalGroupName:data[0].dname  //模板组名称 比如无锡测试
        })
       
        wx.request({
          url: app.globalData.url+"FindTimeModal",
          type:"post",
          header:header,
          data:{
            modalId:modalID
          },
          success:function(res){           
            let data = res.data
           
            //{name: "时段灯" ,turnOff: "16:47:00" ,turnOffChange: "0" ,turnOn: "16:44:00" .turnOnChange: "0"}
            that.setData({             
              ligthTypeStr:data.name, 
              halfLightOff:data.turnOff, 
              cleanLightOn:data.turnOn
            })

            //step1 从modalGroup里面 根据 modalGroup找到是哪个模板组 找到改模板组的id 即对应吓一跳协议的参数gid
            let tmp_modalGroup = that.data.ModalGroup
            let tmp_modalGroupName = that.data.ModalGroupName
            let findModalGroupName = false

            tmp_modalGroup.forEach(function(item, index) {
              if(item.name == tmp_modalGroupName){
                that.setData({
                  cur_group_id:item.id
                })
                findModalGroupName = true
                return false;
              }              
            })

            //说明在已知的模板组里面没有到该模板 比如沛县龙固镇         
            if(findModalGroupName === false){
              wx.showToast({
                title: '抱歉,暂未找到该模板无法修改！',
                icon:'success',
                duration:2000
              }) 
              
              that.setData({
                firstsetupflag:true
              })

              return
            }
          
            //step2 开始获取模板用于显示
            wx.request({
              header:header,
              type:"post",
              url: app.globalData.url+'GetLightModal',
              data:{
                userid:app.globalData.userid,
                gid:that.data.cur_group_id
              },
              success:function(res) {
                //"[{\"turnOff\":\"auto\",\"turnOffChange\":\"1\",\"gid\":\"23\",\"modalType\":\"0\",\"turnOn\":\"auto\",\"name\":\"全夜灯\",\"id\":\"54\",\"turnOnChange\":\"1\",\"group\":\"无锡测试\"},{\"turnOff\":\"23:00:00\",\"turnOffChange\":\"0\",\"gid\":\"23\",\"modalType\":\"1\",\"turnOn\":\"auto\",\"name\":\"半夜灯\",\"id\":\"55\",\"turnOnChange\":\"-45\",\"group\":\"无锡测试\"},{\"turnOff\":\"15:35:00\",\"turnOffChange\":\"0\",\"gid\":\"23\",\"modalType\":\"3\",\"turnOn\":\"15:30:00\",\"name\":\"时段灯\",\"id\":\"57\",\"turnOnChange\":\"0\",\"group\":\"无锡测试\"}]"
                let modaldata = JSON.parse(res.data.data) 
                that.setData({
                  LightModal:modaldata
                })
                let cur_modal = []
                modaldata.forEach(function(item, index) {
                  if(item.name == that.data.ligthTypeStr){
                    cur_modal = item
                    that.setData({
                      change_LightModal_index:index, //这个时候找到具体是那个模板，以及那个模板的index
                      //template_name:cur_modal.name,
                      modalGroupID:item.id,
                      // timeparam_clear_lamp_turnon:item.turnOn,//时段/清洁灯开灯时间
                      // timeparam_clear_lamp_turnoff:item.turnOff,//时段/清洁灯关灯时间
                      // addVal: item.turnOffChange, // 日出调整量
                      // subVal: item.turnOnChange, // 日落调整量
                    })
                    that.data.types.forEach(function(item2, index) {
                      if(item2.value == cur_modal.modalType){
                        that.setData({
                          change_types_index:index
                        })

                        //全夜灯 指定开关等时间类型 为根据设备所在经纬度自动调整
                        if(item2.value == 0){
                          that.setData({
                            change_switchTypes_index:1,  //更具设备所在经纬度自动字段
                            change_timeparam_clear_lamp_turnon:'auto',
                            change_sun_off_disable:true,  //日落时间调整量可用
                            change_subVal:cur_modal.turnOnChange, // 日落调整量
                            change_switchTypes_off_index:1,  //更具设备所在经纬度自动字段
                            change_timeparam_clear_lamp_turnoff:'auto',
                            change_sun_on_disable:true,  //日出时间调整量可用
                            change_addVal: cur_modal.turnOffChange, // 日出调整量
                          })
                        }

                        //半夜灯
                        if( item2.value == 1){
                          that.setData({
                            change_switchTypes_index:1,  //更具设备所在经纬度自动字段
                            change_timeparam_clear_lamp_turnon:'auto',
                            change_sun_off_disable:true,  //日落时间调整量可用
                            change_subVal:cur_modal.turnOnChange, // 日落调整量
                            change_switchTypes_off_index:0,  //指定时间
                            change_timeparam_clear_lamp_turnoff:cur_modal.turnOff,
                            change_sun_on_disable:false,  //日出时间调整量可用
                            change_addVal: 0, // 日出调整量
                          })
                        }

                        //清洁灯 指定开关等时间类型 指定时间
                        if(item2.value == 2 ){
                          that.setData({
                            change_switchTypes_index:0,  //指定时间
                            change_timeparam_clear_lamp_turnon:cur_modal.turnOn, //情节灯开灯时间可以设置
                            change_sun_off_disable:true,  //日落时间调整量可用
                            change_subVal:cur_modal.turnOnChange, // 日落调整量
                            change_switchTypes_off_index:0,  //指定时间
                            change_timeparam_clear_lamp_turnoff:cur_modal.turnOff, //时段半夜灯关灯时间
                            change_sun_on_disable:true,  //日出时间调整量可用
                            change_addVal: cur_modal.turnOffChange, // 日出调整量
                          })
                        }

                        //时段灯
                        if(item2.value == 3){
                          that.setData({
                            change_switchTypes_index:0,  //指定时间
                            change_timeparam_clear_lamp_turnon:cur_modal.turnOn, //时段/清洁灯开灯时间可以设置
                            change_sun_off_disable:false,  //日落时间调整量可用
                            change_subVal:0, // 日落调整量
                            change_switchTypes_off_index:0,  //指定时间
                            change_timeparam_clear_lamp_turnoff:cur_modal.turnOff, //时段半夜灯关灯时间
                            change_sun_on_disable:false,  //日出时间调整量可用
                            change_addVal: 0 // 日出调整量
                          })
                        }

                        return false
                      }                        
                    })
                    return false
                  }                  
                })

                //console.log(that.data, "that.data")
              }
            })  
          }                   
        })
      }
    })



  },

  //点击新建模板
  addnewTemplate:function(e){
    let that = this
    that.setData({
      newtemplateflag:false,
      firstsetupflag:true
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    

  },

  radio_change_status:function(e){    
    let that = this
    let cur_mid = e.currentTarget.dataset.mid
    let tmp_check =  e.currentTarget.dataset.check
    let tmp_name =  e.currentTarget.dataset.name
    let radioStatus = false

    //取反
    if(tmp_check === true){
      radioStatus = false
    }

    if(tmp_check === false){
      radioStatus = true
    }

    let cur_data_array = that.data.items

    cur_data_array.forEach(function(item, index){
       if(item.mid == cur_mid){
         item.radioStatus = radioStatus
         console.log(tmp_name + radioStatus, "check name")
         return false
       }
    })

    that.setData({
      items:cur_data_array
    })
  }
})